package com.hl.card.modular.packBack.controller;

import com.alibaba.fastjson.JSONObject;
import com.hl.card.common.controller.BaseController;
import com.hl.card.common.persistence.model.Goods;
import com.hl.card.common.util.HttpUtils;
import com.hl.card.common.util.MD5Tools;
import com.hl.card.common.util.ResponseObject;
import com.hl.card.core.log.LogObjectHolder;
import com.hl.card.core.shiro.ShiroKit;
import com.hl.card.modular.packBack.service.GoodsSevice;
import com.hl.card.modular.system.service.IAccessRight;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 参数设置控制器
 *
 * @author huangpu
 * @Date 2018-04-06 11:33:32
 */
@Controller
@RequestMapping("/access")
public class SysOptAccessController extends BaseController {
    @Resource
    private IAccessRight accessRight;

    @Resource
    private GoodsSevice goodsSevice;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private String PREFIX = "/packback/sysOptAccess/";

    /**
     * 检查访问操作权限
     */
    @RequestMapping("/checkAccess")
    public String checkAccess(HttpServletRequest request, Model model) {
        String clientIP = getIpAddr(request);
//        List<Map<String, Object>> list= goodsSevice.selectList();
//        for(Object obj:list) {
//            Goods goods = (Goods) obj;
//            System.out.println("good:" + goods.getSeries() + goods.getNowtype());
//        }
        Boolean result = accessRight.checkSysOptAccessRight(clientIP);
        if(!result) {
            System.out.println("授权失败:" + clientIP);
            return PREFIX + "sys_opt_access.html";
        }
        if(result) {
            System.out.println("授权成功:" + clientIP);
            String redirectUrl = stringRedisTemplate.opsForValue().get(clientIP + "redirectUrl");
            return redirectUrl;
        }
        System.out.println("授权失败:" + clientIP);
        return PREFIX + "sys_opt_access.html";
    }

    @PostMapping(value = "/getAccessRight")
    @ResponseBody
    public String getAccessRight(HttpServletRequest request) {
        String accessCode = request.getParameter("accessCode");//短信授权码
        String clientIP = getIpAddr(request);
        String accessPhone = stringRedisTemplate.opsForValue().get("SUPER:ACCESS:ADMIN_PHONE:MANUAL_AWARD");
        Boolean access = accessRight.getAccessRight(accessPhone, accessCode, clientIP);

        ResponseObject reObj=new ResponseObject();
        reObj.setErroCode(1);
        reObj.setData("授权失败");
        if(access) {
            reObj.setErroCode(0);
            reObj.setData("获取授权成功");
            return stringRedisTemplate.opsForValue().get(clientIP + "redirectUrl");
        }
        return "授权失败";
    }

    @PostMapping(value = "/sendAccessCode")
    @ResponseBody
    public ResponseObject sendAccessCode(HttpServletRequest request) {
        String clientIP = getIpAddr(request);
        String accessPhone = stringRedisTemplate.opsForValue().get("SUPER:ACCESS:ADMIN_PHONE:MANUAL_AWARD");
        Boolean result = accessRight.sendSMSCode(accessPhone, clientIP);

        ResponseObject reObj=new ResponseObject();
        reObj.setErroCode(1);
        reObj.setData("发送失败");
        if(result) {
            reObj.setErroCode(0);
            reObj.setData("获取授权成功");
        }
        return reObj;
    }

    /*--------------------------------微信扫一扫授权------------------------------*/
    /**
     * 检查访问操作权限,如果授权失败，返回微信授权码
     */
    @RequestMapping("/getWxAccess")
    @ResponseBody
    public String getWxAccess(HttpServletRequest request, ModelMap model) {
        String clientIP = getIpAddr(request);
        String account = "null";
        String appId = request.getParameter("appId");
        String wxOpenId = request.getParameter("wxUserId");
        String rightCode = request.getParameter("accessCode");
        Boolean result = accessRight.getWxAccessRight(wxOpenId, rightCode, clientIP);
        if(!result) {
            System.out.println("授权失败:" + clientIP);
            return PREFIX + "wxAccessQrError.html";
        }

        System.out.println("授权成功:" + account + "-" + clientIP);
        return PREFIX + "wxAccessSuccess.html";
    }

    @PostMapping(value = "/checkWxAccessRight")
    @ResponseBody
    public ResponseObject checkWxAccessRight(HttpServletRequest request) {
        String clientIP = getIpAddr(request);
        String accessCode = request.getParameter("accessCode");
        System.out.println("授权CODE:" + accessCode);
        String accessInfo = stringRedisTemplate.opsForValue().get("SUPER:" + accessCode);
        JSONObject accessInfoObj = JSONObject.parseObject(accessInfo);
        String optId = accessInfoObj.getString("optId");
        Boolean access = accessRight.checkWxSysOptAccessRight(optId, clientIP);

        ResponseObject reObj=new ResponseObject();
        reObj.setErroCode(1);
        reObj.setData("授权失败");
        if(access) {
            reObj.setErroCode(0);
            reObj.setData("获取授权成功");
            return reObj;
        }
        return reObj;
    }

    @GetMapping(value = "/getAccessInfo")
    @ResponseBody
    public ResponseObject getAccessInfo(HttpServletRequest request) {
        String clientIP = getIpAddr(request);
        String appId = request.getParameter("appId");
        String accessCode = request.getParameter("accessCode");
        String wxUserId = request.getParameter("wxUserId");
        String accessPhone = stringRedisTemplate.opsForValue().get("SUPER:ACCESS:ADMIN_PHONE:MANUAL_AWARD");
        Boolean result = accessRight.sendSMSCode(accessPhone, clientIP);

        ResponseObject reObj=new ResponseObject();
        reObj.setErroCode(1);
        reObj.setData("发送失败");
        if(result) {
            reObj.setErroCode(0);
            reObj.setData("获取授权成功");
        }
        return reObj;
    }

    public String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        // ipAddress = this.getRequest().getRemoteAddr();
        return ipAddress;
    }
}
